package com.dhy.qigsawsplitdownloader

import android.os.Bundle
import android.system.Os
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import org.apache.commons.io.FileUtils
import java.io.File

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val realFile = File(filesDir, "real.txt")
        val linkFile = File(cacheDir, "real.txt")
        if (!realFile.exists()) {
            FileUtils.writeByteArrayToFile(realFile, "This is content".toByteArray())
        }
        btReadFile.setOnClickListener {
            if (realFile.exists()) realFile.readText().toast()
            else "File not found".toast()
        }
        btDeleteFile.setOnClickListener {
            if (realFile.exists()) realFile.delete()
        }
        btLinkFile.setOnClickListener {
            try {
                Os.symlink(realFile.absolutePath, linkFile.absolutePath)
            } catch (e: Exception) {
                e.printStackTrace()
                e.message?.toast()
            }
        }
        btDeleteLinkFile.setOnClickListener {
            if (linkFile.exists()) linkFile.delete()
        }
        btReadLinkFile.setOnClickListener {
            if (linkFile.exists()) linkFile.readText().toast()
            else "File not found".toast()
        }
        btShowLink.setOnClickListener {
            linkFile.exists().toString().toast()
        }
    }

    fun String.toast() {
        Toast.makeText(this@MainActivity, this, Toast.LENGTH_SHORT).show()
    }
}